/*
 * Copyright 2025 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.samples.apps.nowinandroid.demo.viewmodel

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.android.gms.common.util.CollectionUtils.listOf
import com.google.samples.apps.nowinandroid.demo.api.MovieApi
import com.google.samples.apps.nowinandroid.demo.model.MovieList
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Inject

/**
 * 电影列表视图模型
 * 负责管理电影数据的获取和状态管理
 */
@HiltViewModel
class MovieListViewModel @Inject constructor() : ViewModel() {
    /** 电影列表数据流 */
    private val _movieLists = MutableStateFlow<List<MovieList>>(emptyList())
    val movieLists: StateFlow<List<MovieList>> = _movieLists.asStateFlow()

    /** 加载状态数据流 */
    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()

    /** 错误信息数据流 */
    private val _error = MutableStateFlow<String?>(null)
    val error: StateFlow<String?> = _error.asStateFlow()

    /** 搜索关键词数据流 */
    private val _searchQuery = MutableStateFlow("")
    val searchQuery: StateFlow<String> = _searchQuery.asStateFlow()

    /** 是否正在刷新数据流 */
    private val _isRefreshing = MutableStateFlow(false)
    val isRefreshing: StateFlow<Boolean> = _isRefreshing.asStateFlow()

    /** Retrofit 实例，用于网络请求 */
    private val retrofit = Retrofit.Builder()
        .baseUrl(MovieApi.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    /** API 接口实例 */
    private val movieListApi = retrofit.create(MovieApi::class.java)

    init {
        Log.d("tongkeqiang", "MovieListViewModel init block called")
        // 监听搜索关键词变化
        viewModelScope.launch {
            searchQuery
                .debounce(500) // 防抖，500ms 内不触发
                .filter { it.isNotBlank() } // 过滤空字符串
                .distinctUntilChanged() // 过滤重复值
                .collect { query ->
                    loadMovies(query)
                }
        }
    }

    /**
     * 更新搜索关键词
     * @param query 搜索关键词
     */
    fun updateSearchQuery(query: String) {
        _searchQuery.value = query
    }

    /**
     * 加载电影数据
     * @param searchTitle 搜索关键词
     */
    private fun loadMovies(searchTitle: String) {
        viewModelScope.launch {
            try {
                _isLoading.value = true
                _error.value = null
                Log.d("tongkeqiang", "Starting to load movies")
                Log.d("tongkeqiang", "Requesting movies from API")
                val movieList = movieListApi.getMovieList(
                    apiKey = "2a251d3",
                    searchTitle = searchTitle
                )
                _movieLists.value = listOf(movieList)
                Log.d("tongkeqiang", "Processed movies: " + movieLists.value)
                Log.d("tongkeqiang", "Processed movies size: " + movieLists.value.size)
            } catch (e: Exception) {
                _error.value = e.message ?: "加载电影列表失败"
            } finally {
                _isLoading.value = false
                _isRefreshing.value = false
                Log.d("tongkeqiang", "Finished loading movies")
            }
        }
    }

    /**
     * 刷新电影列表
     */
    fun refresh() {
        _isRefreshing.value = true
        loadMovies(_searchQuery.value)
    }

    /**
     * 重试加载数据
     */
    fun retry() {
        loadMovies(_searchQuery.value)
    }
} 